<template>
  <div class="product-manage">
    <div class="product-num"
      >产品库已有<span>{{ total }}</span
      >件商品</div
    >
    <BasicTable row-key="id" @register="registerTable">
      <template #headerTop>
        <Tabs v-model:activeKey="activeKey" type="card" @change="handleTabChange">
          <TabPane v-for="v in tabsData" :key="v.key" :tab="v.title"></TabPane>
        </Tabs>
        <div style="margin: 10px">
          <Button @click="handleRegisterOfflineProducts(getSelectRowKeys())">批量下架</Button>
        </div>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'productName'">
          <div class="product-image-text">
            <div class="img">
              <Image
                :src="record.imageUrl"
                width="67px"
                height="67px"
                style="object-fit: cover"
              ></Image>
            </div>
            <div class="text-box">
              <Tooltip :title="record.productName">
                <span class="product-name">{{ record.productName }}</span>
              </Tooltip>

              <span
                v-if="record.reviewStatus == ReviewStatus.Pending"
                class="label reviewStatus-boder"
                >审核中</span
              >
              <span
                v-else-if="record.opPublishStatus == OPpublishStatus.NotPublished"
                class="label opPublishStatus-boder"
                >被下架</span
              >
              <span
                v-else-if="record.publishStatus == PublishStatus.NotPublished"
                class="label publishStatus-boder"
                >已下架</span
              >
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'shopName'">
          <div class="image-text">
            <Avatar :src="record.shopLogo" />
            <div class="text">{{ record.shopName }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'userName'">
          <div class="image-text">
            <Avatar :src="record.userAvatar" />
            <div class="text">
              <span>{{ record.userName }}</span>
              <span>{{ record.userPhone }}</span>
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'minPrice'">
          <Price :min-price="record.minPrice" :max-price="record.maxPrice" :price-show-type="record.priceShowType"/>
        </template>
        <template v-else-if="column.key === 'memberName'">
          <div v-if="record.memberName" class="image-text">
            <Avatar :src="record.memberLogo" />
            <div class="text">
              <span>{{ record.memberName }}</span>
              <span>{{ record.levelName }}</span>
            </div>
          </div>
          <div v-else class="image-text">
            <Avatar :src="record.shopLogo" />
            <div class="text">{{ record.shopName }}</div>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '详情',
                onClick: () => handleAdd(1, record),
              },
              record.opPublishStatus != OPpublishStatus.NotPublished &&
              record.publishStatus == PublishStatus.Published
                ? {
                    label: '下架',
                    onClick: () => handleRegisterOfflineProducts([record.id]),
                  }
                : {},
              {
                label: '下架记录',
                onClick: () => handleOpenRegisterOfflineProductsLog(record.id),
              },
            ]"
          />
        </template>
        <template v-if="column.key === 'logisticsMode'">
          <span>{{
            dictionary.logisticsMode.find((v) => v.dictValue === record.logisticsMode)?.dictLabel
          }}</span>
        </template>
      </template>
    </BasicTable>
    <ProductLibDetail @register="register" @reload="reload"></ProductLibDetail>
    <OfflineProducts
      @register="registerOfflineProducts"
      @reload="() => tabsData[activeKey].handleReload()"
    ></OfflineProducts>
    <OfflineProductsLog @register="registerOfflineProductsLog"></OfflineProductsLog>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema } from '@/components/Table';
  import { getProductCategory, getProductLibList } from '@/api/hby/productManage/index';
  import Dictionary from '@/utils/dictionary';
  import { Image, Tabs, TabPane, Button, Avatar, Tooltip } from 'ant-design-vue';
  import { IProductManage, IProductResult } from '@/api/hby/productManage/type';
  import ProductLibDetail from './ProductLibDetail.vue';
  import { useModal } from '@/components/Modal';
  import { OPpublishStatus, PublishStatus, ReviewStatus } from '@/enums/productManage';
  import { formatMoney } from '@/utils/number';
  import dictionary from '@/utils/dictionary/localDicts';
  import OfflineProducts from './OfflineProducts.vue';
  import OfflineProductsLog from './OfflineProductsLog.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { productCategoryList } from '@/api/hby/categoryManagement';
  import { isArray } from '@/utils/is';
  import Price from "@/components/Price/index.vue";


  const { createMessage } = useMessage();
  const dicts = Dictionary.getLocalMulti([
    'productType',
    'productReviewStatus',
    'productReviewMenu',
  ]);

  const tableSchemas = reactive<FormSchema[]>([
    {
      field: `keyWord`,
      label: `搜索产品`,
      component: 'Input',
      componentProps: {
        placeholder: '输入商品名称/组织名称/发布者信息/会员信息',
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: `productCategoryId`,
      label: `产品分类`,
      component: 'ApiCascader',
      componentProps: {
        api: productCategoryList,
        isLoadData: false,
        initFetchParams: { size: 999 },
        labelField: 'name',
        valueField: 'id',
        isLeaf: (record) => {
          return !record.children
        },
        showLastLabel: true,
        showSearch: true,
        filterOption: (input: string, option: any) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: `[startTime, endTime]`,
      label: `最近修改`,
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm:ss',
        placeholder: ['开始时间', '结束时间'],
        showTime: { format: 'HH:mm:ss' },
      },
      colProps: {
        span: 8,
      },
    },
    {
      field: `productType`,
      label: `产品类型`,
      component: 'Select',
      componentProps: {
        fieldNames: { label: 'dictLabel', value: 'dictValue' },
        options: dicts.productType,
      },
      colProps: {
        span: 4,
      },
    },
  ]);

  // 详情
  const [register, { openModal }] = useModal();

  function handleAdd(type: number, row: IProductResult) {
    openModal(true, {
      type,
      row,
    });
  }

  // 下架
  const [registerOfflineProducts, { openModal: openModalRegisterOfflineProducts }] = useModal();

  const handleRegisterOfflineProducts = (ids: string[]) => {
    if (!ids.length) {
      createMessage.warning('请选择要下架的产品');
      return;
    }
    openModalRegisterOfflineProducts(true, { ids });
  };

  // 下架记录
  const [registerOfflineProductsLog, { openModal: openRegisterOfflineProductsLog }] = useModal();

  const handleOpenRegisterOfflineProductsLog = (id: number) => {
    openRegisterOfflineProductsLog(true, { id });
  };

  const total = ref(0);

  const [registerTable, { reload, getSelectRowKeys, clearSelectedRowKeys, getRawDataSource }] =
    useTable({
      api: (params: any) => {
        clearSelectedRowKeys();
        if(isArray(params.productCategoryId)){
          params.productCategoryId = params.productCategoryId[params.productCategoryId.length - 1];
        }
        params = { ...params, ...unref(filterInfo) };
        return getProductLibList(params);
      },
      columns: [
        {
          title: '商品信息',
          dataIndex: 'productName',
          width: 272,
          align: 'center',
        },
        {
          title: '价格',
          dataIndex: 'minPrice',
          width: 150,
          align: 'center',
        },
        {
          title: '产品类型',
          dataIndex: 'productType',
          width: 100,
          align: 'center',
        },
        {
          title: '产品类目',
          dataIndex: 'categoryName',
          width: 100,
          align: 'center',
        },

        {
          title: '产品来源',
          dataIndex: 'shopName',
          width: 240,
          align: 'center',
        },
        {
          title: '发布者',
          dataIndex: 'userName',
          width: 214,
          align: 'center',
        },
        {
          title: '会员信息',
          dataIndex: 'memberName',
          width: 214,
          align: 'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 200,
          align: 'center',
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          width: 200,
        },
      ],
      showIndexColumn: true,
      clickToRowSelect: false,
      useSearchForm: true,
      showTableSetting: true,
      tableSetting: {
        redo: false,
        size: false,
        setting: false,
        fullScreen: false,
      },
      formConfig: {
        labelWidth: 100,
        schemas: tableSchemas as unknown as FormSchema[],
      },
      actionColumn: {
        width: 200,
        title: '操作',
        dataIndex: 'action',
      },
      rowSelection: {
        getCheckboxProps(record: IProductManage) {
          return {
            disabled:
              record.opPublishStatus == OPpublishStatus.NotPublished ||
              record.publishStatus == PublishStatus.NotPublished ||
              record.reviewStatus == ReviewStatus.Pending,
          };
        },
      },
      afterFetch: (data: IProductManage[]) => {
        total.value = getRawDataSource().total;
        return data.map((item) => {
          return {
            ...item,
            productType: dicts.productType.find((v) => v.dictValue == item.productType)?.dictLabel,
            reviewStatusText: dicts.productReviewStatus.find(
              (v) => v.dictValue === item.reviewStatus,
            )?.dictLabel,
          
          };
        });
      },
    });

  // 勾选

  const activeKey = ref('0');
  const filterInfo = ref<Recordable>({});
  // tabs
  const tabsData = reactive([
    {
      title: '全部',
      key: '0',
      handleReload() {
        filterInfo.value = {};
        reload({ page: 1 });
      },
    },
    {
      title: '上架中',
      key: '1',
      handleReload() {
        filterInfo.value = { publishStatus: PublishStatus.Published };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '下架中',
      key: '2',
      handleReload() {
        filterInfo.value = { publishStatus: PublishStatus.NotPublished };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '审核中',
      key: '3',
      handleReload() {
        filterInfo.value = { reviewStatus: ReviewStatus.Pending };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
    {
      title: '被下架',
      key: '4',
      handleReload() {
        filterInfo.value = {
          publishStatus: PublishStatus.NotPublished,
          opPublishStatus: OPpublishStatus.NotPublished,
        };
        reload({ filterInfo: unref(filterInfo), page: 1 });
      },
    },
  ]);

  const handleTabChange = (val: string) => {
    tabsData[val].handleReload();
  };
</script>

<style lang="less" scoped>
  .product-manage {
    .product-num {
      padding: 16px;
      padding-bottom: 0;
      color: #1d2129;
      font-family: 'PingFang SC';
      font-size: 20px;
      font-style: normal;
      font-weight: 400;
      line-height: 28px;
      span {
        color: #2878ff;
        font-family: 'PingFang SC';
        font-size: 20px;
        font-style: normal;
        font-weight: 400;
        line-height: 28px;
      }
    }
    ::v-deep .ant-table-title {
      & > div {
        & > div {
          margin: 0 !important;
        }
      }
      .ant-tabs-nav {
        margin: 0 !important;
      }
    }
    .product-image-text {
      display: flex;
      gap: 16px;
      .text-box {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .product-name {
          text-align: left;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2; /* 定义文本的行数 */
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-all;
          white-space: normal; /* 保证文本换行 */
          line-height: 1.6; /* 根据需要调整行高 */
          max-height: 3.2em; /* 行高乘以行数 */
        }
        .label {
          padding: 3px 8px;
          border: 1px solid;
          width: fit-content;
        }
        .reviewStatus-boder {
          border-color: #2878ff;
          background-color: white;
          color: #2878ff;
        }
        .opPublishStatus-boder {
          border-color: #f53f3f;
          background-color: white;
          color: #f53f3f;
        }
        .publishStatus-boder {
          border: none;
          background-color: #f2f3f5;
          color: #1d2129;
        }
      }
    }

    .image-text {
      display: flex;
      align-items: center;
      gap: 16px;

      .text {
        flex: 1;
        display: flex;
        flex-direction: column;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
</style>
